package com.audi.activity;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.R;
import com.audi.adapter.AddActionCardAdapter;
import com.audi.adapter.SQLiteAsusNewHelper;
import com.audi.dto.DeviceItem;
import com.audi.dto.PlaceItem;
import com.audi.dto.SceneItem;
import com.audi.dto.SmartTriggerItem;
import com.audi.dto.SmartTriggerTriggerItem;
import com.audi.dto.SmartTriggerWhenItem;
import com.audi.dto.SmartTriggerWhenTriggerItem;
import com.audi.message.ActionMessage;
import com.audi.message.SendMessage;
import com.audi.utils.Constants;
import com.audi.utils.DBHelper;
import com.audi.utils.DeviceHelper;
import com.audi.view.DialogSelectActionTrigger;

/**
 * @author NamNT16: use case 5-3-2 (database test with box ver 1)
 */
@SuppressLint("ResourceAsColor")
public class AddActionCardActivity extends Activity {
	private ArrayList<String> mtime, mplug;
	private AddActionCardAdapter mSmartTriggerAdapter;
	LinearLayout ltime, lplug;
	public ImageButton lcheck;
	LinearLayout lnRowDevice, decriptionTrig;
	Activity activity;
	ListView listTrigger;
	ImageButton iconDeviceWhen, iconDeviceThen;
	TextView textwhen, textThen, textRoomWhen, textRoomThen;
	TableLayout tbLayout;
	Button cancel;
	Button done;
	TextView txtThen;
	ImageButton menuleft;
	ImageButton btnWhen, btnThen;
	DeviceItem devWhen, devThen;
	int CREATE_NEW_TRIG;// default =0;
	int DONE_WHEN = 0;// default =0
	int DONE_THEN = 0;
	int EDIT_TRIG = 0;// defaulf=0;
	int chooseImage = 0;
	SmartTriggerWhenItem mSTwhenItem = new SmartTriggerWhenItem();
	SmartTriggerTriggerItem mSTthenItem = new SmartTriggerTriggerItem();
	SmartTriggerItem mSmartTriggerItem = new SmartTriggerItem();
	SmartTriggerWhenTriggerItem mSmartTriggerWhenTriggerItem = new SmartTriggerWhenTriggerItem();
	SQLiteAsusNewHelper mSQLHelper;
	DeviceHelper deviceHelper = new DeviceHelper();
	DialogSelectActionTrigger slAction;
	LinearLayout layoutchose, layoutThen;
	ArrayList<DeviceItem> list = new ArrayList<DeviceItem>();
	ArrayList<DeviceItem> listLoadDevice = new ArrayList<DeviceItem>();
	ArrayList<SceneItem> listScene = new ArrayList<SceneItem>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		activity = this;
		setContentView(R.layout.activity_add_action_card);
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		EDIT_TRIG = bundle.getInt("TYPE_ACTION");
		
		try {
			bundle = getIntent().getExtras();
			mSmartTriggerItem = (SmartTriggerItem) bundle.getSerializable("TriggerItem");
			mSTwhenItem=mSmartTriggerItem.getWhen();
			mSTthenItem=mSmartTriggerItem.getTrigger();
			mSmartTriggerWhenTriggerItem=mSmartTriggerItem.getWhenTrigger();
//			Log.e("dasdsadsdsd", "+++++++++++++++data_trigg="+mSmartTriggerItem);
//			Log.d("dasdsadsdsd", "+++++++++++++++data_trigg()="+mSTwhenItem.getWhenDeviceId());
//			Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDevicePlaceId());
//			Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDeviceName());
//			Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDevicePlaceName());
//			Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDeviceType());
//			Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDeviceValues());
			
		} catch (Exception e) {
			Log.d("LOIdfdfdfdfdfdf", "+++++++++++767676767="+e );
		}
		SendMessage message = new SendMessage();
		message.getListDevice(deviceHandle);
		message.sendData(ActionMessage.GET_LIST_SCENE, null, getListScene);
		initactionCreate();

	}

	public void initactionCreate() {
		slAction = new DialogSelectActionTrigger(activity);
		tbLayout = (TableLayout) findViewById(R.id.bangtest);
		mtime = new ArrayList<String>();
		mtime.add("Every day at");
		mtime.add("Every hour at");
		mtime.add("Every day of the week at");
		mplug = new ArrayList<String>();
		mplug.add("Switched ON");
		mplug.add("Switched OFF");
		decriptionTrig = (LinearLayout) findViewById(R.id.decrip_smart_trigger);
		decriptionTrig.setVisibility(View.GONE);
		iconDeviceWhen = (ImageButton) findViewById(R.id.btnWhen1);
		iconDeviceThen = (ImageButton) findViewById(R.id.btnCondition1);
		textwhen = (TextView) findViewById(R.id.txt_when1);
		textThen = (TextView) findViewById(R.id.txt_condition1);
		textRoomWhen = (TextView) findViewById(R.id.txt_room);
		textRoomThen = (TextView) findViewById(R.id.txt_room1);
		layoutchose = (LinearLayout) findViewById(R.id.chosse_action);
		layoutThen = (LinearLayout) findViewById(R.id.action_then);
		lcheck = (ImageButton) findViewById(R.id.btn_check);
		btnWhen = (ImageButton) findViewById(R.id.btn_chosse_action_when);
		btnThen = (ImageButton) findViewById(R.id.btn_chosse_action_then);
		txtThen = (TextView) findViewById(R.id.txt_then_);
		ImageView btnNotification = (ImageView) findViewById(R.id.btn_on_off_notification);
		// bat tat thong bao trigger
		btnNotification.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				_OnOffnotification();

			}
		});

		// list=mSQLHelper.getListDeviceTrigg();

		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayShowHomeEnabled(false);
		mActionBar.setDisplayShowTitleEnabled(false);
		LayoutInflater mInflater = LayoutInflater.from(this);

		View mCustomView = mInflater.inflate(R.layout.action_bar_trigger, null);
		ImageButton deleteBtn = (ImageButton) mCustomView
				.findViewById(R.id.btn_menu_devices_card);
		menuleft = (ImageButton) mCustomView
				.findViewById(R.id.btn_devices_name_drawer);

		cancel = (Button) mCustomView.findViewById(R.id.cancel);
		cancel.setVisibility(View.VISIBLE);
		done = (Button) mCustomView.findViewById(R.id.done);
		done.setVisibility(View.VISIBLE);
		done.setAlpha(0.5f);
		done.setEnabled(false);
		done.setTextColor(getResources().getColor(R.color.gray));
		mActionBar.setCustomView(mCustomView);
		mActionBar.setDisplayShowCustomEnabled(true);
		textRoomWhen.setVisibility(View.INVISIBLE);
		textRoomThen.setVisibility(View.INVISIBLE);

		// khi edit trigger EDIT_TRIG==1
		if (EDIT_TRIG == 1) {
			// menuleft.setVisibility(View.INVISIBLE);

			menuleft.setImageResource(R.drawable.icon_back);
			iconDeviceThen.setImageResource(R.drawable.trigger_when);
			iconDeviceWhen.setImageResource(R.drawable.trigger_when);
			cancel.setVisibility(View.GONE);
			done.setVisibility(View.GONE);
			tbLayout.setVisibility(View.GONE);
			layoutchose.setVisibility(View.VISIBLE);
			textwhen.setText(mSTwhenItem.getWhenDeviceName());
			textThen.setText(mSTthenItem.getTriggerDeviceName());
			
			textRoomThen.setVisibility(View.VISIBLE);
			textRoomWhen.setVisibility(View.VISIBLE);
			textRoomWhen.setText(mSTwhenItem.getWhenDevicePlaceName());
			textRoomThen.setText(mSTthenItem.getTriggerDevicePlaceName());
			deleteBtn.setImageResource(R.drawable.icon_recycle);
			decriptionTrig.setVisibility(View.VISIBLE);
			deleteBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					finish();
					Toast.makeText(getApplicationContext(), "Delete",
							Toast.LENGTH_LONG).show();
				}
			});
			// 1111 icon click
						iconDeviceWhen.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								chooseImage = 0;
								selectDevice();
								DONE_THEN=1;
								DONE_WHEN = 0;
								selecActionTrigger();
								
								txtThen.setTextColor(getResources().getColor(
										R.color.color_title_place_info));
								
								Log.e("================", "++++++++edit===....");
							}
						});
						iconDeviceThen.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub

								chooseImage = 1;
								selectDevice();
								DONE_WHEN = 1;

								Log.e("================", "++++++++edit");
							}
						});
		} else {
			// selectDevice();
			txtThen.setTextColor(getResources().getColor(R.color.black));
			layoutchose.setVisibility(View.GONE);
			Log.e("================", "++++++++edit");
			deleteBtn.setVisibility(View.GONE);
			menuleft.setVisibility(View.INVISIBLE);
			textwhen.setAlpha(0.5f);
			textThen.setAlpha(0.5f);

			// 1212 icon click
			iconDeviceWhen.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					chooseImage = 0;
					selectDevice();
					selecActionTrigger();
					DONE_WHEN = 0;
					txtThen.setTextColor(getResources().getColor(
							R.color.color_title_place_info));
					Log.e("================", "++++++++edit===....");
				}
			});
			iconDeviceThen.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					chooseImage = 1;
					selectDevice();
					DONE_WHEN = 1;

					Log.e("================", "++++++++edit");
				}
			});
		}

		cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// /selectDevice();
				finish();
			}
		});
		menuleft.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				selectDevice();
				finish();
			}
		});
		done.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// Toast.makeText(getApplicationContext(), "Done",
				// Toast.LENGTH_LONG).show();
				// finish();
				SendMessage addWHENTHEN = new SendMessage();
				mSmartTriggerWhenTriggerItem.setOnOff(1);
				mSmartTriggerWhenTriggerItem.setWhenTriggerName("co ho");
				addWHENTHEN.sendData(ActionMessage.ADD_WHEN_TRIGGER_ST,
						mSmartTriggerWhenTriggerItem,
						addSmartTriggerWhenTrigger);

			}
		});
		btnWhen.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// selecActionTrigger(1);
				// selectDevice();
				txtThen.setTextColor(getResources().getColor(
						R.color.color_title_place_info));
				slAction.selectAction(mSTwhenItem, null);
			}
		});
		btnThen.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// selectactionWhen();
				// selectDevice();
				// txtThen.setTextColor(getResources().getColor(
				// R.color.color_title_place_info));
				slAction.selectAction(null, mSTthenItem);
			}
		});
		//555 check before done (save new trigger)
		lcheck.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (EDIT_TRIG == 0) {
					//finish();								
				try {
					
					SendMessage message = new SendMessage();
					message.sendData(ActionMessage.ADD_WHEN_ST, mSTwhenItem,
							addSmartTriggerWhen);
					message.sendData(ActionMessage.ADD_TRIGGER_ST, mSTthenItem,
							addSmartTriggerThen);
				} catch (Exception e) {
					Log.d("send add when then",
							"send add when then: " + e.toString());
				}
				Log.e("check	=========	", "check logic >>>>>>>>>>>");
				// done.invalidate();
				done.setAlpha(1);
				done.setTextColor(getResources().getColor(
						R.color.action_bar_color));
				done.setEnabled(true);
				}else{
					//556
					Toast.makeText(getApplicationContext(), "Finish Edit",
							Toast.LENGTH_LONG).show();
					Log.e("check	=========	", "check logic before edit>>>>>>>>>>>");
					
					Log.e("dasdsadsdsd", "+++++++++++++++data_trigg="+mSmartTriggerItem);
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg()-===="+mSTwhenItem.getWhenDeviceId());
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDevicePlaceId());
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDeviceName());
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDevicePlaceName());
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSTwhenItem.getWhenDeviceType());
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg=<><><>"+mSTwhenItem.getWhenDeviceValues());
					Log.e("dasdsadsdsd", "--------------------------="+mSmartTriggerWhenTriggerItem);
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg()-===="+mSmartTriggerWhenTriggerItem.getTriggerId());
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSmartTriggerWhenTriggerItem.getWhenId());
					Log.d("dasdsadsdsd", "+++++++++++++++data_trigg="+mSmartTriggerWhenTriggerItem.getWhenTriggerName());
					
					try {
						SendMessage message = new SendMessage();
						message.sendData(ActionMessage.UPDATE_WHEN_ST, mSTwhenItem,
								updateSTwhen);
						message.sendData(ActionMessage.UPDATE_TRIGGER_ST, mSTthenItem,
								updateSTthen);
						message.sendData(ActionMessage.UPDATE_WHEN_TRIGGER_ST, mSmartTriggerWhenTriggerItem,
								updateSTwhenthen);
					} catch (Exception e) {
						Log.v("==============", "CO LOI KHI UPDATe ==="+e);
					}
				}
			}
		});
	}

	public void innitOnclick() {
	}

	// ///////////////////////
	// phuong thuc chon when//
	public void selecActionTrigger() {
		if (DONE_THEN == 1) {
			layoutThen.setVisibility(View.VISIBLE);
		} else {
			layoutThen.setVisibility(View.INVISIBLE);

		}

		// tbLayout.setVisibility(View.VISIBLE);
	}

	public ArrayList<DeviceItem> filterDevice() {
		ArrayList<DeviceItem> listResult = new ArrayList<DeviceItem>();
		if (chooseImage == 0) {
			listResult.clear();
			for (int j = 0; j < list.size(); j++) {
				Log.d("LOG=========", "========0 handle running=======>>>>>>>"
						+ list.get(j).getDeviceType());
				switch (list.get(j).getDeviceType()) {

				case 10:
					break;

				default:
					listResult.add(list.get(j));
					break;
				}

			}
			list.clear();
			list = listResult;
		} else if (chooseImage == 1) {
			listResult.clear();
			for (int j = 0; j < list.size(); j++) {
				Log.d("LOG=========", "========1 -handle running=======>>>>>>>"
						+ list.get(j).getDeviceType());
				switch (list.get(j).getDeviceType()) {

				case 0:
				case 1:
				case 2:
				case 10:
					listResult.add(list.get(j));
					break;

				default:

					break;
				}
			}
			for (int indexScene = 0; indexScene < listScene.size(); indexScene++) {
				SceneItem itemScene = listScene.get(indexScene);
				DeviceItem itemDevice = new DeviceItem();
				itemDevice.setDeviceId(itemScene.getSceneId());
				itemDevice.setDeviceName(itemScene.getSceneTitle());
				itemDevice.setDeviceIcon(itemScene.getSceneIcon());
				itemDevice.setDeviceStatus(0);
				itemDevice.setDeviceType(Constants.DEVICE_TYPE.TRIGGER_SCENE
						.ordinal());
				itemDevice.setStatusValue(0);
				itemDevice.setDeviceCode("SSSS");
				itemDevice.setDeviceBoxId(0);
				itemDevice.setDevicePlaceId(itemScene.getPlaceId());
				itemDevice.setDevicePlace(itemScene.getScenePlace());
				itemDevice.setUserId(1);
				listResult.add(itemDevice);
			}

		}
		return listResult;
	}

	public void selectDevice() {
		layoutchose.setVisibility(View.GONE);
		listTrigger = (ListView) findViewById(R.id.list_action);
		tbLayout.removeAllViews();// clear table
		tbLayout.setVisibility(View.VISIBLE);
		if (list.size() > 0) {
			listLoadDevice = filterDevice();
		}
		final TableRow row = new TableRow(getApplicationContext());
		row.setOrientation(LinearLayout.VERTICAL);
		row.setGravity(Gravity.CENTER);
		final ViewGroup placeholder = row;
		int i = 0;
		for (; i < listLoadDevice.size(); i++) {
			Log.e("=======", "======devide " + i);
			final int position = i;
			lnRowDevice = new LinearLayout(getApplicationContext());
			lnRowDevice.invalidate();
			lnRowDevice.setOrientation(LinearLayout.VERTICAL);
			lnRowDevice.setGravity(Gravity.CENTER);

			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					130, 130);
			LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			p.weight = 1;
			// Toast.makeText(getApplicationContext(), i+"==",
			// Toast.LENGTH_SHORT).show();
			lnRowDevice.setPadding(35, 0, 35, 5);
			// lnRowDevice.setLayoutParams(layoutParams);
			lnRowDevice.setTag(i);
			lnRowDevice.setId(i);
			final ImageView imageView = new ImageView(getApplicationContext());
			int width = 120;
			int height = 120;
			// imageView.setBackgroundColor(Color.GRAY);
			LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(
					width, height);

			// imageView.setPadding(25, 25, 25, 25);
			imageView.setLayoutParams(parms);

			// imageView.setBackgroundColor(Color.BLUE);
			imageView
					.setBackgroundResource(R.drawable.icon_device_no_icon_small);
			imageView.setImageResource(R.color.transparent);
			final TextView textview = new TextView(getApplicationContext());
			final TextView textviewRoom = new TextView(getApplicationContext());
			textview.setGravity(Gravity.CENTER);
			textview.setTextColor(Color.BLACK);
			textview.setEllipsize(TextUtils.TruncateAt.END);
			textview.setMaxLines(1);
			textview.setLayoutParams(p);
			textview.setText(" " + listLoadDevice.get(i).getDeviceName());

			textviewRoom.setText(listLoadDevice.get(position).getDevicePlace());
			textviewRoom.setGravity(Gravity.CENTER);
			textviewRoom.setTextSize(12);
			textviewRoom.setLayoutParams(p);
			final ImageView imageChooseItem = new ImageView(
					getApplicationContext());
			imageChooseItem
					.setBackgroundResource(R.drawable.choose_item_trigger);
			imageChooseItem.setImageResource(R.color.transparent);
			LinearLayout.LayoutParams parmsChooseImge = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			parmsChooseImge.setMargins(0, 0, 0, 5);
			imageChooseItem.setLayoutParams(parmsChooseImge);
			// /imageChooseItem.setId(i);
			imageChooseItem.setVisibility(View.INVISIBLE);

			lnRowDevice.addView(imageChooseItem);
			lnRowDevice.addView(imageView);
			lnRowDevice.addView(textview);
			lnRowDevice.addView(textviewRoom);

			lnRowDevice.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (DONE_WHEN == 0) {
						if (((LinearLayout) placeholder.findViewById(v.getId()))
								.getChildAt(0).getVisibility() == View.VISIBLE) {
							tbLayout.setVisibility(View.GONE);
							layoutchose.setVisibility(View.VISIBLE);
							// layoutThen.setVisibility(View.INVISIBLE);
							iconDeviceWhen
									.setImageResource(R.drawable.trigger_when);
							textwhen.setText(listLoadDevice.get(position)
									.getDeviceName());
							textRoomWhen.setText(listLoadDevice.get(position)
									.getDevicePlace());
							textRoomWhen.setVisibility(View.VISIBLE);
							// DONE_WHEN = 1;
							textThen.setAlpha(1);
							textwhen.setAlpha(1);

							devWhen = listLoadDevice.get(v.getId());
							setWhenTriggerItem(devWhen);
							slAction.initDesWhenThen(mSTwhenItem, null);
						} else {
							for (int j2 = 0; j2 < listLoadDevice.size(); j2++) {
								if (j2 == v.getId()) {
									((LinearLayout) placeholder
											.findViewById(j2)).getChildAt(0)
											.setVisibility(View.VISIBLE);
								} else {
									((LinearLayout) placeholder
											.findViewById(j2)).getChildAt(0)
											.setVisibility(View.INVISIBLE);
								}
							}
						}
					} else if (DONE_WHEN == 1) {

						if (((LinearLayout) placeholder.findViewById(v.getId()))
								.getChildAt(0).getVisibility() == View.VISIBLE) {
							tbLayout.setVisibility(View.GONE);
							layoutchose.setVisibility(View.VISIBLE);
							layoutThen.setVisibility(View.VISIBLE);
							DONE_THEN = 1;
							Log.d("Done when 1", ">>>>>>done when 0 <<<");
							textThen.setAlpha(1);
							textThen.setText(listLoadDevice.get(position)
									.getDeviceName());
							textRoomThen.setText(listLoadDevice.get(position)
									.getDevicePlace());
							textRoomThen.setVisibility(View.VISIBLE);
							iconDeviceThen
									.setImageResource(R.drawable.trigger_when);
							devThen = listLoadDevice.get(v.getId());
							setThenTriggerItem(devThen);
							slAction.initDesWhenThen(null, mSTthenItem);
							decriptionTrig.setVisibility(View.VISIBLE);
							loadDescriptionHomeAction();
						} else {
							for (int j2 = 0; j2 < listLoadDevice.size(); j2++) {
								if (j2 == v.getId()) {
									((LinearLayout) placeholder
											.findViewById(j2)).getChildAt(0)
											.setVisibility(View.VISIBLE);
								} else {
									((LinearLayout) placeholder
											.findViewById(j2)).getChildAt(0)
											.setVisibility(View.INVISIBLE);
								}
							}
						}

					}

					// Log.d("DEdeeeeeeeeeeeeeeeeeeeee",
					// ">>>>>>"+devWhen.getDeviceName());
				}
			});

			placeholder.addView(lnRowDevice);
		}
		tbLayout.addView(placeholder);

	}

	public void loadDescriptionHomeAction() {
		TextView deviceNameWhen = (TextView) findViewById(R.id.chon_dk_finish_device_when);
		TextView deviceNameWhenAction = (TextView) findViewById(R.id.chon_dk_finish_device_when_action);
		TextView deviceNameThen = (TextView) findViewById(R.id.chon_dk_finish_device_then);
		TextView deviceNameThenAction = (TextView) findViewById(R.id.chon_dk_finish_device_then_action);
		deviceNameWhen.setText(slAction.desWhen);
		deviceNameThen.setText(slAction.desThen);
	}

	public void selectthen() {
		tbLayout.invalidate();
		layoutchose.invalidate();
		layoutThen.invalidate();
		tbLayout.setVisibility(View.VISIBLE);
		layoutchose.setVisibility(View.GONE);
		layoutThen.setVisibility(View.VISIBLE);
	}

	// lay list device tu BOX
	Handler deviceHandle = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					Log.d("LOG=========", "===== get list device");
					try {
						Log.d("LOG=========", "===== get list device");
						if (msg.arg1 != -1) {
							list.clear();
							ArrayList<DeviceItem> result = (ArrayList<DeviceItem>) msg
									.getData()
									.getSerializable(
											String.valueOf(ActionMessage.getAllDeviceList));
							list = result;
							DeviceItem item2 = new DeviceItem();
							item2.setDeviceId(90000);
							item2.setDeviceName("Time");
							item2.setDeviceIcon("");
							item2.setDeviceStatus(21);
							item2.setDeviceType(Constants.DEVICE_TYPE.TIME
									.ordinal());
							item2.setStatusValue(21);
							item2.setDeviceCode("SSSS");
							item2.setDeviceBoxId(0);
							item2.setDevicePlaceId(3);
							item2.setUserId(1);
							list.add(0, item2);

							DeviceItem item1 = new DeviceItem();
							item1.setDeviceId(90001);
							item1.setDeviceName("Member status");
							item1.setDeviceIcon("");
							item1.setDeviceStatus(21);
							item1.setDeviceType(Constants.DEVICE_TYPE.MEMSTATUSHOME
									.ordinal());
							item1.setStatusValue(21);
							item1.setDeviceCode("SSSS");
							item1.setDeviceBoxId(0);
							item1.setDevicePlaceId(3);
							item1.setUserId(1);
							list.add(1, item1);

							Log.d("LOG=========",
									"========handle running=======>>>>>>>");
							Log.d("LOG=========", "=====" + result);
							Log.d("LOG=========", "===============>>>>>>>");

						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL==========]:" + e.toString());
					}
				}
			});
		}
	};

	public void _OnOffnotification() {
		final LinearLayout layout = (LinearLayout) findViewById(R.id.ln_notification);
		ImageView btn_noti = (ImageView) findViewById(R.id.btn_on_off_notification);
		if (layout.getAlpha() == 1) {
			layout.setAlpha(0.5f);

			btn_noti.setImageDrawable(getResources().getDrawable(
					R.drawable.btn_place_card_onoff_off));
		} else {
			layout.setAlpha(1);
			btn_noti.setImageDrawable(getResources().getDrawable(
					R.drawable.btn_place_card_onoff_on));
		}

	}

	private SmartTriggerWhenItem setWhenTriggerItem(DeviceItem deviceWHEN) {
		mSTwhenItem.setWhenDeviceId(deviceWHEN.getDeviceId());
		mSTwhenItem.setWhenDeviceType(deviceWHEN.getDeviceType());
		mSTwhenItem.setWhenDeviceValues("");
		mSTwhenItem.setWhenDeviceName(deviceWHEN.getDeviceName());
		mSTwhenItem.setWhenDevicePlaceId(deviceWHEN.getDevicePlaceId());
		mSTwhenItem.setWhenDevicePlaceName(deviceWHEN.getDevicePlace());
		return null;
	}

	private SmartTriggerTriggerItem setThenTriggerItem(DeviceItem deviceTHEN) {
		mSTthenItem.setTriggerDeviceId(deviceTHEN.getDeviceId());
		mSTthenItem.setTriggerDeviceType(deviceTHEN.getDeviceType());
		mSTthenItem.setTriggerDeviceValues("");
		mSTthenItem.setTriggerDeviceName(deviceTHEN.getDeviceName());
		mSTthenItem.setTriggerDevicePlaceId(deviceTHEN.getDevicePlaceId());
		mSTthenItem.setTriggerDevicePlaceName(deviceTHEN.getDevicePlace());
		return null;
	}

	private SmartTriggerItem setSmarItem(DeviceItem deviceItem) {
		mSmartTriggerItem.setWhenId(mSTwhenItem.getWhenId());
		mSmartTriggerItem.setTriggerId(mSTthenItem.getTriggerId());
		mSmartTriggerItem.getSmarttriggername();

		return null;
	}

	/**
	 * getListScene
	 * 
	 * @param Handler
	 *            callBack
	 * @see get list Scene
	 */
	@SuppressLint("HandlerLeak")
	Handler getListScene = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						Log.d("LOG=========", "=====  get list Scene");
						if (msg.arg1 != -1) {
							listScene.clear();
							@SuppressWarnings("unchecked")
							ArrayList<SceneItem> result = (ArrayList<SceneItem>) msg
									.getData()
									.getSerializable(
											String.valueOf(ActionMessage.GET_LIST_SCENE));
							listScene = result;
						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL==========]:" + e.toString());
					}
				}
			});
		}
	};

	/**
	 * addSTWhen
	 * 
	 * @param Handler
	 *            callBack
	 * @see add SmartTriggerWhen
	 */
	@SuppressLint("HandlerLeak")
	Handler addSmartTriggerWhen = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						Log.d("LOG=========", "=====  addSmartTriggerWhen");
						if (msg.arg1 != -1) {

							int idTriggerWhen = msg.getData().getInt(
									String.valueOf(ActionMessage.ADD_WHEN_ST));
							if (idTriggerWhen > 0) {
								mSmartTriggerWhenTriggerItem
										.setWhenId(idTriggerWhen);
							}
						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL==========]:" + e.toString());
					}
				}
			});
		}
	};
	/**
	 * addSTThen
	 * 
	 * @param Handler
	 *            callBack
	 * @see add addSmartTriggerThen
	 */
	@SuppressLint("HandlerLeak")
	Handler addSmartTriggerThen = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						Log.d("LOG=========", "=====  addSmartTriggerThen");
						if (msg.arg1 != -1) {

							int idTriggerThen = msg
									.getData()
									.getInt(String
											.valueOf(ActionMessage.ADD_TRIGGER_ST));
							if (idTriggerThen > 0) {
								mSmartTriggerWhenTriggerItem
										.setTriggerId(idTriggerThen);
							}
						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL==========]:" + e.toString());
					}
				}
			});
		}
	};
	/**
	 * addSmartTriggerWhenTrigger
	 * 
	 * @param Handler
	 *            callBack
	 * @see add addSmartTriggerWhenTrigger
	 */
	@SuppressLint("HandlerLeak")
	Handler addSmartTriggerWhenTrigger = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						Log.d("LOG=========",
								"=====  addSmartTriggerWhenTrigger");
						if (msg.arg1 != -1) {

							int idTriggerThen = msg
									.getData()
									.getInt(String
											.valueOf(ActionMessage.ADD_WHEN_TRIGGER_ST));
							if (idTriggerThen > 0) {
								// mSmartTriggerWhenTriggerItem
								// .set(idTriggerThen);
								finish();
							}
						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL==========]:" + e.toString());
					}
				}
			});
		}
	};
	/**
	 * addSmartTriggerWhenTrigger
	 * 
	 * @param Handler
	 *            callBack
	 * @see add addSmartTriggerWhenTrigger
	 */
	@SuppressLint("HandlerLeak")
	Handler updateSTwhen= new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						Log.d("LOG=========",
								"=====  DAng update when ST");
						if (msg.arg1 != -1) {

							int resultUpdateWhen = msg
									.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_WHEN_ST));
							if (resultUpdateWhen > 0) {
								Log.d("LOG=========",
										"===== update when ST oke");
								//finish();
							}else{
								Log.d("LOG=========",
										"===== update when ST ERROR");
							}
						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL==========]:" + e.toString());
					}
				}
			});
		}
	};
	/**
	 * addSmartTriggerWhenTrigger
	 * 
	 * @param Handler
	 *            callBack
	 * @see add addSmartTriggerWhenTrigger
	 */
	@SuppressLint("HandlerLeak")
	Handler updateSTthen= new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						Log.d("LOG=========",
								"=====  DAng update then ST");
						if (msg.arg1 != -1) {

							int resultUpdateThen = msg
									.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_TRIGGER_ST));
							if (resultUpdateThen > 0) {
								Log.d("LOG=========",
										"===== update then ST oke");
								//finish();
							}else{
								Log.d("LOG=========",
										"===== update then ST ERROR");
							}
						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL==========]:" + e.toString());
					}
				}
			});
		}
	};
	/**
	 * addSmartTriggerWhenTrigger
	 * 
	 * @param Handler
	 *            callBack
	 * @see add addSmartTriggerWhenTrigger
	 */
	@SuppressLint("HandlerLeak")
	Handler updateSTwhenthen= new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						Log.d("LOG=========",
								"=====  DAng update whenthen ST");
						if (msg.arg1 != -1) {
							int resultUpdateWhenThen = msg
									.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_WHEN_TRIGGER_ST));
							if (resultUpdateWhenThen > 0) {
								Log.d("LOG=========",
										"===== update whenthen ST oke");
								finish();
							}else{
								Log.d("LOG=========",
										"===== update whenthen ST ERROR");
							}
						}
					} catch (Exception e) {
						Log.e("TEST", "[TUTORIAL==========]:" + e.toString());
					}
				}
			});
		}
	};
}
